package cn.sh.ideal.web.configuration.management.controller;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;

@Controller
@PropertySource(value = { "classpath:jdbc.properties" })
@RequestMapping(value = "/data")
public class assetManagementDataController {

	private RestTemplate rs = new RestTemplate();

	private String[] hostInfoList = { "sh_region;所属域", "sh_sysname;系统名称", "sh_roomname;机房", "sh_rackname;机架",
			"location;设备存放位置", "systemname;所属应用系统", "host_used_for;主机用途", "pn;P/N", "serialon;序列号",
			"modeldesc;型号描述", "clname;配置项名称", "sh_ipaddr;IP地址", "sh_mask;掩码", "sh_ipgateway;网关", "mgraddr;管理卡地址",
			"clcategory;配置项分类", "clcode;搜索代码", "clid;配置项标识", "remark;备注", "devicename;设备名称", "serialnumber;资产编号",
			"usedstatus;使用状态", "mendfactory;维护厂家", "mendpeople;维护联系人", "mendperiod;维护有效期", "mendphone;维护联系电话",
			"region;区域", "buy_date;购置日期", "cablenetcardcount;电口网卡数量", "cbdate;出保日期", "connwithothersys;是否与其他系统共用",
			"cpuinfo;CPU情况", "cpumodel;CPU型号", "cpuspeed;CPU主频", "cputype;CPU类型", "databasever;数据库版本",
			"devicetype;品牌类型", "diskinfo;磁盘信息", "disksize;硬盘大小", "divisioncfg;分区配置", "divisionnpg;分区大小",
			"enableinterface;可用的接口卡数量", "entitycode;实物编码", "fans;风扇数量", "fc_side;FC对端", "havecddriver;是否配光驱",
			"havesubarea;是否有分区", "havetape;是否配磁带机", "hbacardamount;HBA卡数量", "hostid;主机服务器标识", "hostmodel;型号",
			"installdisks;安装的磁盘数量", "iochannel;I/O通道数量", "ipaddress;IP地址", "logiccpu;逻辑CPU数量",
			"logicsubarea;逻辑分区数量", "manufactory;生产厂商", "maxcpucount;满配CPU个数", "maxdiskcount;满配磁盘个数",
			"maxmemslotcount;满配磁盘插槽数量", "memmodel;内存型号", "memnum;内存数量", "mgrcardswitchport;管理卡交换机端口",
			"networkcardamount;网卡数量", "net_side;网络对端", "opticsnetcardinfo;光口网卡数量", "osname;操作系统",
			"outer_sys_inter;外系统接口", "paaaword;口令", "physicscpu;物理CPU数量", "physicsmenory;物理内存大小", "powercount;电源数量",
			"prjname;项目名称", "pepaired_man;维护人", "roomposition;机房位置", "san;SAN", "server_type;服务器类型",
			"switchport;交换机端口", "sw_applation;软件应用", "sw_config;软件配置", "tpcc;TPCC值", "usedmemslotcount;已用内存插槽数量",
			"user_man;使用人" };
	
	@Value("${server_address}")
	private String serverAddress;

	/**
	 * 导入主机信息表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importHostList", method = RequestMethod.POST)
	@ResponseBody
	public int importHostList(@RequestParam("file") MultipartFile file) {

		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		Sheet sheet = null;
		try {
			InputStream fis = file.getInputStream();
			Workbook wb = null;

			if ("xls".equals(fileType)) {
				wb = new HSSFWorkbook(fis);
			} else if ("xlsx".equals(fileType)) {
				wb = new XSSFWorkbook(fis);
			} else {

			}

			sheet = wb.getSheetAt(0);
		} catch (IOException e) {

			e.printStackTrace();
		}
		
		//获取文件内容，并插入数据库
		for (Iterator rowIterator = sheet.iterator(); rowIterator.hasNext();) {
			Row row = (Row) rowIterator.next();

			if (row.getRowNum() == 0) {
				continue;
			}
			
			Map<String, String> hostMap = new HashMap<String, String>();
			for (int i = 0; i < hostInfoList.length; i++) {
				String str = hostInfoList[i].split(";")[0];
				hostMap.put(str, getCellValue(row.getCell(i)));

			}
			//请求出入数据
			String url = serverAddress + "/insertHostInfo";
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
			MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
			params.setAll(hostMap);

			HttpEntity<MultiValueMap<String, String>> requestEntity = 
					new HttpEntity<MultiValueMap<String, String>>(params, headers);
			// 执行HTTP请求
			ResponseEntity<String> response = rs.exchange(url, HttpMethod.POST, requestEntity, String.class);

		}

		return 0;

	}

	@RequestMapping("/getFields")
	@ResponseBody
	public String getFields() {
		String url = serverAddress + "/getFields";

		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
		headers.setContentType(type);
		HttpEntity<String> entity = new HttpEntity<>(new String(), headers);
		ResponseEntity<String> exchange = rs.exchange(url, HttpMethod.GET, entity, String.class);
		String reult = exchange.getBody();

		return reult;

	}

	
	@RequestMapping("/exportHostList1")
	public ResponseEntity<byte[]> exportHostList1() {
		// 请求导出数据
		String url = serverAddress + "/exportHostList1";
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/msexcel;charset=UTF-8;");
		headers.setContentType(type);
		HttpEntity<String> entity = new HttpEntity<>(new String(), headers);
		ResponseEntity<byte[]> exchange = rs.exchange(url, HttpMethod.GET, entity, byte[].class);

		return exchange;
	}

//	@RequestMapping("/exportHostList")
//	@ResponseBody
//	public ResponseEntity<byte[]> exportHostList() {
//
//		// 请求导出数据
//		String url = serverAddress + "/exportHostList";
//		HttpHeaders headers = new HttpHeaders();
//		MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
//		headers.setContentType(type);
//		HttpEntity<String> entity = new HttpEntity<>(new String(), headers);
//		ResponseEntity<String> exchange = rs.exchange(url, HttpMethod.GET, entity, String.class);
//		// 获取导出数据
//		String hody = exchange.getBody();
//
//		List<Map<String, Object>> s = (List<Map<String, Object>>) JSON.parse(hody);
//
//		// 创建文件，并写入数据
//		Workbook workbook = new HSSFWorkbook();
//		// 创建工作表sheet
//		Sheet sheet = workbook.createSheet("host");
//		// 创建第一行
//		Row row = sheet.createRow(0);
//		Cell cell = null;
//
//
//		for (int i = 0; i < hostInfoList.length; i++) {
//			String str = hostInfoList[i].split(";")[1];
//			cell = row.createCell(i);
//			cell.setCellValue(str);
//		}
//
//		for (int i = 0; i < s.size(); i++) {
//			Row nrow = sheet.createRow(i + 1);
//			Map<String, Object> map = s.get(i);
//			for (int j = 0; j < hostInfoList.length; j++) {
//				String str = hostInfoList[j].split(";")[0];
//				Cell ncell = nrow.createCell(j);
//				String value = (String) map.get(str);
//
//				if (null != value || !"".equals(value)) {
//					ncell.setCellValue(value);
//				}
//			}
//		}
//		ByteArrayOutputStream os = new ByteArrayOutputStream();
//
//
//
//		byte[] body = null;
//		try {
//			workbook.write(os);
//			body = os.toByteArray();
//
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//
//		HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
//		HttpHeaders head = new HttpHeaders();// 设置响应头
//		String fileName = "";
//		try {
//			fileName = new String("HostList.xls".getBytes(), "ISO8859-1");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} // 防止中文乱码
//		head.add("Content-Disposition", "attachment;filename=" + fileName);
//		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, head, statusCode);
//
//		return response;
//	}


	@RequestMapping("/exportHostList")
	@ResponseBody
	public ModelAndView exportHostList(HttpServletResponse response) {

		// 请求导出数据
		String url = serverAddress + "/exportHostList";
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
		headers.setContentType(type);
		HttpEntity<String> entity = new HttpEntity<>(new String(), headers);
		ResponseEntity<String> exchange = rs.exchange(url, HttpMethod.GET, entity, String.class);
		// 获取导出数据
		String hody = exchange.getBody();

		List<Map<String, Object>> s = (List<Map<String, Object>>) JSON.parse(hody);

		// 创建文件，并写入数据
		Workbook workbook = new HSSFWorkbook();
		// 创建工作表sheet
		Sheet sheet = workbook.createSheet("host");
		// 创建第一行
		Row row = sheet.createRow(0);
		Cell cell = null;


		for (int i = 0; i < hostInfoList.length; i++) {
			String str = hostInfoList[i].split(";")[1];
			cell = row.createCell(i);
			cell.setCellValue(str);
		}

		for (int i = 0; i < s.size(); i++) {
			Row nrow = sheet.createRow(i + 1);
			Map<String, Object> map = s.get(i);
			for (int j = 0; j < hostInfoList.length; j++) {
				String str = hostInfoList[j].split(";")[0];
				Cell ncell = nrow.createCell(j);
				String value = (String) map.get(str);

				if (null != value || !"".equals(value)) {
					ncell.setCellValue(value);
				}
			}
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();



		byte[] body = null;
		try {
			workbook.write(os);
			body = os.toByteArray();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				String fileName = "";
		try {
			fileName = new String("HostList.xls".getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} // 防止中文乱码

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
		try {
			OutputStream ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}



	/**
	 * 插入一条数据
	 * 

	 * @return
	 */
	@RequestMapping("/insertHostInfo")
	@ResponseBody
	public int insertHostInfo(@RequestParam Map<String, String> param) {

		String url = serverAddress + "/insertHostInfo";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.setAll(param);

		HttpEntity<MultiValueMap<String, String>> requestEntity =
				new HttpEntity<MultiValueMap<String, String>>(params, headers);
		ResponseEntity<String> response = rs.exchange(url, HttpMethod.POST, requestEntity, String.class);

		return 0;
	}

	/**
	 * 更新一条主机信息
	 * 
	 * @param param
	 */
	@RequestMapping("/updateHostInfo")
	@ResponseBody
	public int updateHostInfo(@RequestParam Map<String, Object> param) {
		String url = serverAddress + "/updateHostInfo";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
		params.setAll(param);
		
		HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params,	headers);
		// 执行HTTP请求
		ResponseEntity<String> response = rs.exchange(url, HttpMethod.POST, requestEntity, String.class);


		String result = response.getBody();

		return 0;
	}

	/**
	 * 根据查询条件，查询主机信息
	 * 
	 * @param region
	 * @param ipAddr
	 * @param roomName
	 * @param rackName
	 * @return
	 */
	@RequestMapping(path = "/queryHostInfo")
	@ResponseBody
	public String queryHostInfo(@RequestParam("region") String region, @RequestParam("ipAddr") String ipAddr,
			@RequestParam("roomName") String roomName, @RequestParam("rackName") String rackName,
			@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize) {

		String url = serverAddress + "/queryHostInfo?region=" + region + "&ipAddr=" + ipAddr + "&pageSize=" + pageSize
				+ "&roomName=" + roomName + "&rackName=" + rackName + "&page=" + page;

		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
		headers.setContentType(type);
		HttpEntity<String> entity = new HttpEntity<>(new String(), headers);

		ResponseEntity<String> exchange = rs.exchange(url, HttpMethod.GET, entity, String.class);

		String result = exchange.getBody();

		return result;

	}

	/**
	 * 根据条件，删除主机信息
	 * 

	 * @return
	 */
	@RequestMapping("/deleteHostInfo")
	@ResponseBody
	public String deleteHostInfo(@RequestParam("ids") String ids) {

		String url = serverAddress + "/deleteHostInfo?ids=" + ids;

		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
		headers.setContentType(type);
		HttpEntity<String> entity = new HttpEntity<>(new String(), headers);

		ResponseEntity<String> exchange = rs.exchange(url, HttpMethod.GET, entity, String.class);

		String result = exchange.getBody();

		return "s";
	}

	public static String getCellValue(Cell cell) {
		String vlaue = "";
		if (cell.getCellTypeEnum() == CellType.STRING) {
			vlaue = cell.getStringCellValue();

		} else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
			vlaue = cell.getNumericCellValue() + "";

		} else if (cell.getCellTypeEnum() == CellType.FORMULA) {
			vlaue = cell.getCellFormula();
		}

		return vlaue;
	}

}
